package com.ybg.block.core.fabric;

import com.ybg.block.core.dbapi.entity.FabricOrderer;
import com.ybg.block.core.dbapi.entity.FabricOrg;

import com.ybg.block.core.dbapi.service.FabricOrdererService;
import com.ybg.block.core.dbapi.service.FabricOrgService;
import com.ybg.share.core.fabric.FabricOrdererRemoteApi;
import com.ybg.block.core.fabric.datamapper.FabricOrdererDataMapper;
import com.ybg.share.core.fabric.dto.FabricOrdererEditDTO;
import com.ybg.share.core.fabric.vo.FabricOrdererVO;
import com.ybg.framework.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

@Slf4j
@Service(version = "${dubbo.provider.version}", timeout = 120000, cache = "false")
public class FabricOrdererRemoteApiImpl implements FabricOrdererRemoteApi {

    @Autowired
    private FabricOrgService fabricOrgService;
    @Autowired
    private FabricOrdererService fabricOrdererService;


    @Override
    public R<?> editOrderer(FabricOrdererEditDTO dto) {
        FabricOrderer orderer = new FabricOrderer();
        orderer.notify();
        FabricOrg fabricOrg = null;
        FabricOrderer fabricOrderer = null;
        if (dto.getId() == null && dto.getOrgId() == null) {
            return R.fail("组织ID不能为空");
        }
        if (dto.getOrgId() != null) {
            fabricOrg = fabricOrgService.getById(dto.getOrgId());
            if (fabricOrg == null) {
                return R.fail("组织不存在");
            }
            fabricOrderer = fabricOrdererService.getById(dto.getId());
            orderer.setLeagueId(fabricOrg.getLeagueId());
            orderer.setOrgId(dto.getOrgId());
        } else {

            orderer.setCreateTime(LocalDateTime.now());
        }


        orderer.setId(dto.getId());
        orderer.setName(dto.getName());
        orderer.setLocation(dto.getLocation());
        orderer.setServerCrtPath(dto.getServerCrtPath());
        orderer.setClientCertPath(dto.getClientCertPath());
        orderer.setClientKeyPath(dto.getClientKeyPath());
        orderer.setOrgId(dto.getOrgId());
        fabricOrdererService.saveOrUpdate(orderer);
        return R.success();
    }

    @Override
    public R<?> deleteById(Long id) {
        if (id == null) {
            return R.fail("id为空");
        }
        fabricOrdererService.removeById(id);
        // 没有依赖它的模块，所以不需要删除其他的
        return R.success();
    }

    @Override
    public R<FabricOrdererVO> getById(Long id) {

        FabricOrderer fabricOrderer = fabricOrdererService.getById(id);
        if (fabricOrderer == null) {
            return R.fail("数据为空");
        }
        return R.success(FabricOrdererDataMapper.INSTANCE.toVO(fabricOrderer));
    }


}
